const fs = require('fs'),
  path = require('path'),
  os = require('os'),
  FileUtil = require('./node/file')

function listFiles (pathname, files) {
  const _files = fs.readdirSync(pathname)
  _files.forEach(f => {
    f = path.join(pathname, f)
    if (FileUtil.isDir(f)) {
      listFiles(f, files)
    } else if (f.endsWith('.js')) {
      files.push(f)
    }
  })
}

const files = [],
  pathname = `${process.cwd()}/node/install/darwin`.replace(/\\+/g, '/'),
  packages = fs.readdirSync(pathname)

listFiles(pathname, files)

files.forEach(filename => {
  filename = filename.replace(/\\+/g, '/')
  let content = FileUtil.readFile(filename).split('\n')
  content.forEach((text, index) => {
    packages.forEach(packagename => {
      if (text.indexOf(`require('${packagename}`) != -1) {
        let relative_length = filename.replace(`${pathname}/`, '').split('/').length,
          relative_path = []
        for (let i = 0; i < relative_length - 1; i++) {
          relative_path.splice(0, 0, '..')
        }
        content[index] = text.replace(`require('${packagename}`, `require('${relative_path.join('/')}/${packagename}`)
      } else if (text.indexOf(`require("${packagename}`) != -1) {
        let relative_length = filename.replace(`${pathname}/`, '').split('/').length,
          relative_path = []
        for (let i = 0; i < relative_length - 1; i++) {
          relative_path.splice(0, 0, '..')
        }
        content[index] = text.replace(`require("${packagename}`, `require("${relative_path.join('/')}/${packagename}`)
      }
    })
  })
  FileUtil.write(filename, content.join('\n'))
})